package com.github.gexiao.middleware.hystrix;

import com.github.gexiao.middleware.hystrix.annotation.DoHystrix;
import com.github.gexiao.middleware.hystrix.service.HystrixHandler;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;

@Aspect
public class DoHystrixAspect {
    private final Logger logger = LoggerFactory.getLogger(DoHystrixAspect.class);

    @Pointcut("@annotation(com.github.gexiao.middleware.hystrix.annotation.DoHystrix)")
    public void aopPoint() {

    }

    @Around("aopPoint() && @annotation(doHystrix)")
    public Object doRouter(ProceedingJoinPoint pjp, DoHystrix doHystrix) throws Throwable {
        Method method = getMethod(pjp);
        HystrixHandler hystrixHandler = (HystrixHandler) doHystrix.hystrixHandler().newInstance();
        return hystrixHandler.access(pjp, method, doHystrix, pjp.getArgs());

    }

    private Method getMethod(JoinPoint jp) throws NoSuchMethodException {
        Signature sig = jp.getSignature();
        MethodSignature methodSignature = (MethodSignature) sig;
        return jp.getTarget().getClass().getMethod(methodSignature.getName(), methodSignature.getParameterTypes());
    }

}
